package com.lz.action;

import java.awt.Canvas;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import com.lz.form.UploadItemDTO;
import com.lz.service.ItemCategoryService;
import com.lz.service.UploadItemService;
import com.lz.util.PropertyReader;

public class UploadItemAction extends DispatchAction {

    String filePath = "";

    /**
     * This method is invoked when the Admin comes to Manage items page.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward load(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
	
	
	      if(!LoginAction.isAdmin(request)){
	        request.setAttribute("message","You are not logged in as administrator");
	    	return mapping.findForward("MESSAGE");
	        }
        filePath = getServlet().getServletContext().getRealPath("/")
                + "gallery";

        System.out.println("Inside load");
        UploadItemDTO uform = (UploadItemDTO) form;
        String shopId = uform.getShopid();
        ArrayList list = UploadItemService.getItemsList(shopId);
        uform.setImageList(list);
        List categoryList = ItemCategoryService.getAllCategory();
        
        request.setAttribute("categorylist",categoryList);
        System.out.println("fwd  LOAD");
        
  
        
        return mapping.findForward("LOAD");
    }

    /**
     * This method is invoked to show the page for update. This method fetches the item details
     * to be displayed on the update page
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward loadModify(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
	
	      if(!LoginAction.isAdmin(request)){
	            request.setAttribute("message","You are not logged in as administrator");
	    	return mapping.findForward("MESSAGE");
	        }
        filePath = getServlet().getServletContext().getRealPath("/")
                + "gallery";
        
        UploadItemDTO uform = (UploadItemDTO) form;
 

        uform = UploadItemService.getItemDetails(uform);
        

        System.out.println("fwd  LOADMODIFY");
        return mapping.findForward("LOADMODIFY");
    }

    /**
     * This is invoked to update the item details [updateDescription could better be updateDetails] 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward updateDescription(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
	
	      if(!LoginAction.isAdmin(request)){
	            request.setAttribute("message","You are not logged in as administrator");
	    	return mapping.findForward("MESSAGE");
	        }
        filePath = getServlet().getServletContext().getRealPath("/")
                + "gallery";
        
        UploadItemDTO uform = (UploadItemDTO) form;
  
        UploadItemService.updateItemDetails(uform);


        return load(mapping, form, request, response);
    }

    /**
     * To delete an item 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
	      if(!LoginAction.isAdmin(request)){
	            request.setAttribute("message","You are not logged in as administrator");
	    	return mapping.findForward("MESSAGE");
	        }
        filePath = getServlet().getServletContext().getRealPath("/")
                + "gallery";
        System.out.println("Inside delete");
        UploadItemDTO uform = (UploadItemDTO) form;
        String shopId = uform.getShopid();
        String imageId = uform.getImageId();

        UploadItemService.deleteItem(shopId, imageId);
        deleteFile(shopId, imageId);
        System.out.println("Shop Id " + shopId);
        System.out.println("Image Id " + imageId);

        return load(mapping, form, request, response);
    }

    /**
     * To delete the images in the folder both original and thumbnail
     * @param shopId
     * @param imageId
     */
    private void deleteFile(String shopId, String imageId) {
        File forg = new File(filePath + File.separator + shopId
                + File.separator + imageId);
        File fthumb = new File(filePath + File.separator + shopId
                + File.separator + "thumb_" + imageId);

        try {
            //delete the original and thumbnail 
            forg.delete();
            fthumb.delete();
            forg = null;
            fthumb = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Invoked when creatinga new item along with an image.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward upload(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
	      if(!LoginAction.isAdmin(request)){
	            request.setAttribute("message","You are not logged in as administrator");
	    	return mapping.findForward("MESSAGE");
	        }
        filePath = getServlet().getServletContext().getRealPath("/")
                + "gallery";

        

        UploadItemDTO uform = (UploadItemDTO) form;
        FormFile myFile = uform.getPhoto();
        int fileSize = myFile.getFileSize();
        
        if(fileSize <= 0 || fileSize > (1.5 * 1024 *1000)){
            request.setAttribute("MESSAGE","Invalid File size. File size cannot be more than 1.5 MB or less than 0 KB");
        }
        else
        {
        
        String fileName = myFile.getFileName();

        String ext = "";
        if (fileName.indexOf(".") > 0) {
            ext = fileName.substring(fileName.lastIndexOf('.'), fileName
                    .length());
        }

        //generate a unique file name and save it
        String outFileName = System.currentTimeMillis() + ext;
        saveImage(myFile, uform.getShopid(), outFileName);

        uform.setImageId(outFileName);
        uform.setPhoto(null);
        myFile = null;
        UploadItemService.uploadGallery(uform);
        }
        
        String shopId = uform.getShopid();
        ArrayList list = UploadItemService.getItemsList(shopId);
        uform.setImageList(list);

        System.out.println("fwd  LOAD");
        
        List categorylist = ItemCategoryService.getAllCategory();
        
        request.setAttribute("categorylist",categorylist);
        return mapping.findForward("LOAD");
    }

    
    private void saveImage(FormFile file, String shopId, String outFileName)
    throws Exception {

String fileName = file.getFileName();

FileOutputStream fileOutStream = null;
InputStream fis=null;    
try {
    if (!fileName.equals("")) {
        fis = file.getInputStream();
        
        String outputFolder = filePath + File.separator + shopId;
        File fileToCreate = new File(outputFolder, "ORG_" + outFileName);
        fileToCreate.getParentFile().mkdirs();
        

        if (fileToCreate.exists()) {
            fileToCreate.delete();
        }

        fileOutStream = new FileOutputStream(fileToCreate);
        byte[] buffer = new byte[1024*50];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1){
            fileOutStream.write(buffer, 0, bytesRead); // write
          }
        fileOutStream.flush();
        
        
        if (fileOutStream != null) {
            fileOutStream.close();

        }

       resizeImage(outputFolder + File.separator + "ORG_" + outFileName,
                outputFolder + File.separator + outFileName, Integer.parseInt(PropertyReader.getConfigProperty("imgheight")), 
		Integer.parseInt(PropertyReader.getConfigProperty("imgwidth")));
        
        createThumbmail(outputFolder + File.separator + outFileName,
                outputFolder + File.separator + "thumb_" + outFileName);
        
        fileToCreate.delete();

    }
} finally {
    if (fileOutStream != null) {
        fileOutStream.close();

    }
    
    if (fis != null) {
        fis.close();

    }            

}

}


    
    private void resizeImage(String srcFile, String destFile,int imageHeight,int imageWidth) throws IOException {
        String fileType = "jpg";

     
        File fsrc = new File(srcFile);
        File fdest = new File(destFile);

        BufferedImage originalBufferedImage = ImageIO.read(fsrc);

        int originalWidth = originalBufferedImage.getWidth();
        int originalHeight = originalBufferedImage.getHeight();

        double scale = 0;

        if (((double) imageWidth / originalWidth) < ((double) imageHeight / originalHeight)) {

            scale = (double) imageWidth / originalWidth;

        } else {

            scale = (double) imageHeight / originalHeight;

        }

        int width = (int) (originalWidth * scale);
        int height = (int) (originalHeight * scale);

        BufferedImage newBufferedImage = new BufferedImage(width, height,
                originalBufferedImage.getType());

        Graphics2D graphics2D = newBufferedImage.createGraphics();

        Canvas dummyObserver = new Canvas();

        Image scaledImage = originalBufferedImage.getScaledInstance(width,
                height, Image.SCALE_SMOOTH);

        graphics2D.drawImage(scaledImage, 0, 0, dummyObserver);

        javax.imageio.ImageIO.write(newBufferedImage, fileType, fdest);
    }

    public void createThumbmail(String srcFile, String destFile)
            throws IOException {
	
	resizeImage(srcFile, destFile, Integer.parseInt(PropertyReader.getConfigProperty("thumbnailheight")), 
		Integer.parseInt(PropertyReader.getConfigProperty("thumbnailwidth")));
	
       
    }

       
         
     
  

}
